<template>
  <view class="viewport">
    <fui-nav-bar
      isOccupy
      isFixed
      background="#0052D9"
      title="报修申请"
      color="#fff"
      @leftClick="leftClick"
    >
      <fui-icon color="#fff" name="arrowleft"></fui-icon>
    </fui-nav-bar>

    <view class="warp">
      <scroll-view
        class="scroll-view"
        :refresher-triggered="refreshing"
        scroll-y="true"
        lower-threshold="20"
        @scrolltolower="onScrollToLower"
        @refresherrefresh="onRefresh"
      >
        <view class="warp">
          <view class="port">
            <view class="title">
              <fui-section
                title="设备信息"
                fontWeight="500"
                descrSize="25"
                color="#666"
                lineWidth="4px"
                isLine
              ></fui-section>
            </view>
            <fui-input
              required
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="deviceName"
              label="设备名称"
              :bottomLeft="0"
              placeholder="请选择设备"
              @click="handleDeviceSelect"
            >
              <fui-icon :size="50" name="arrowright" color="#0052D9"></fui-icon>
            </fui-input>
            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="deviceCode"
              label="设备编号"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="deviceModel"
              label="规格型号"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="deviceType"
              label="设备类型"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="storageLocation"
              label="存放位置"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="deptName"
              label="使用部门"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
          </view>

          <view class="port">
            <view class="title">
              <fui-section
                title="报修信息"
                fontWeight="500"
                descrSize="25"
                color="#666"
                lineWidth="4px"
                isLine
              ></fui-section>
            </view>
            <fui-input
              required
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="applyCode"
              label="报修单号"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              required
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="applyTitle"
              label="报修主题"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="applyUser"
              label="报修人"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="applyDept"
              label="所属部门"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="contactInfo"
              label="联系方式"
              :bottomLeft="0"
              placeholder="请输入"
            ></fui-input>
          </view>

          <view class="port">
            <view class="title">
              <fui-section
                title="报修信息"
                fontWeight="500"
                descrSize="25"
                color="#666"
                lineWidth="4px"
                isLine
              ></fui-section>
            </view>
            <fui-input
              required
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="faultDate"
              label="故障时间"
              :bottomLeft="0"
              placeholder="请输入"
            >
              <fui-icon
                :size="50"
                name="arrowright"
                @click="showFaultDate = true"
              ></fui-icon>
            </fui-input>

            <fui-input
              :padding="['28rpx', '40rpx']"
              labelSize="32rpx"
              v-model="faultType"
              label="故障类别"
              :bottomLeft="0"
              placeholder="请输入"
              @click="showFaultType = true"
            >
              <fui-icon :size="50" name="arrowright"></fui-icon>
            </fui-input>

            <fui-bottom-popup
              :show="showFaultType"
              @close="showFaultType = false"
            >
              <view class="fault-type-popup">
                <view class="popup-header">
                  <text>请选择故障类别</text>
                  <view class="popup-buttons">
                    <text class="cancel-btn" @click="showFaultType = false"
                      >取消</text
                    >
                    <text class="confirm-btn" @click="confirmFaultType"
                      >确定</text
                    >
                  </view>
                </view>
                <view class="fault-type-content">
                  <!-- 左侧父级列表 -->
                  <scroll-view class="parent-list" scroll-y>
                    <view
                      class="parent-item"
                      v-for="(item, index) in faultTypeList"
                      :key="item.id"
                      :class="{ selected: selectedParentIndex === index }"
                      @click="selectParent(index)"
                    >
                      {{ item.faultTypeName }}
                    </view>
                  </scroll-view>
                  <!-- 右侧子级列表 -->
                  <scroll-view class="child-list" scroll-y>
                    <view
                      class="child-item"
                      v-for="(item, index) in currentChildren"
                      :key="index"
                      :class="{ selected: selectedChildIndex === index }"
                      @click="selectChild(index)"
                    >
                      {{ item }}
                    </view>
                  </scroll-view>
                </view>
              </view>
            </fui-bottom-popup>

            <view class="li">
              <view class="left">故障等级</view>
              <view class="right">
                <fui-data-tag
                  width="100"
                  background="#f6f6f6"
                  :padding="['10rpx', '10rpx']"
                  :options="options"
                  @change="change"
                ></fui-data-tag>
              </view>
            </view>

            <view class="li">
              <view class="left">是否停机</view>
              <view class="right"
                ><fui-switch scaleRatio="0.8" checked></fui-switch
              ></view>
            </view>

            <fui-textarea
              required
              labelSize="32rpx"
              :padding="['28rpx', '40rpx']"
              flexStart
              label="故障描述"
              placeholder="请输入内容"
            ></fui-textarea>
          </view>

          <view class="port">
            <view class="title">
              <fui-section
                title="故障图片"
                fontWeight="500"
                descrSize="25"
                color="#666"
                lineWidth="4px"
                isLine
              ></fui-section>
              <fui-icon :size="50" name="camera" @click="team"></fui-icon>
            </view>
            <view class="tishi">上传图片（最多上传10张）</view>
            <div class="grid-container">
              <div class="grid-item" v-for="v of 7" :key="v">
                <image
                  class="img"
                  src="/static/images/my/background-Img.png"
                  mode=""
                ></image>
              </div>
            </div>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="footer">
      <button class="submit-btn" type="primary" @click="submit">提交</button>
    </view>

    <up-calendar
      :show="showFaultDate"
      :mode="mode"
      @confirm="confirmFaultDate"
      @close="showFaultDate = false"
    ></up-calendar>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import {
  getFaultTypeList,
  saveRepairApply,
} from "@/pages/api/subpkg_institution/repairworkorder.js";
import { useUserStore } from "@/stores/user.js";

// 设备信息
const deviceName = ref("");
const deviceCode = ref("");
const deviceModel = ref("");
const deviceType = ref("");
const storageLocation = ref("");
const deptName = ref("");
// 报修信息
const applyCode = ref("");
const applyTitle = ref("");
const applyUser = ref("");
const applyDept = ref("");
const contactInfo = ref("");
// 故障信息
const faultDate = ref("");
const faultType = ref("");
const repairLevel = ref("");
const isStop = ref(false);
const faultDesc = ref("");
const faultImage = ref(""); // 这里只做单图片，后续可扩展

const refreshing = ref(false);
const options = ref(["紧急", "高", "中", "低"]);

const showFaultDate = ref(false);
const mode = ref("single");
const showFaultType = ref(false);
const faultTypeList = ref([]);
const selectedParentIndex = ref(0);
const selectedChildIndex = ref(-1);

// 获取故障类型列表
const getFaultTypes = async () => {
  try {
    const res = await getFaultTypeList();
    if (res && res.code === 200) {
      // 过滤掉没有children的父级选项
      faultTypeList.value = res.data.filter(
        (item) => item.children && item.children.length > 0
      );
    } else {
      uni.showToast({
        title: res.msg || "获取故障类型失败",
        icon: "none",
      });
    }
  } catch (error) {
    uni.showToast({
      title: "获取故障类型异常",
      icon: "none",
    });
  }
};

const currentChildren = computed(() => {
  if (!faultTypeList.value.length) return [];
  const currentParent = faultTypeList.value[selectedParentIndex.value];
  return currentParent?.children?.map((child) => child.faultTypeName) || [];
});

const selectParent = (index) => {
  selectedParentIndex.value = index;
  selectedChildIndex.value = -1; // 切换父级时重置子级选择
};

const selectChild = (index) => {
  selectedChildIndex.value = index;
};

const confirmFaultType = () => {
  if (selectedChildIndex.value === -1) {
    uni.showToast({
      title: "请选择具体故障类型",
      icon: "none",
    });
    return;
  }
  const parent = faultTypeList.value[selectedParentIndex.value].faultTypeName;
  const child = currentChildren.value[selectedChildIndex.value];
  faultType.value = `${parent}-${child}`;
  showFaultType.value = false;
};

const confirmFaultDate = (e) => {
  console.log(
    "%c [  ]: ",
    "color: #bf2c9f; background: pink; font-size: 13px;",
    e
  );
  faultDate.value = e["0"];
  showFaultDate.value = false;
};

const change = (e) => {
  repairLevel.value = e.detail.value;
};

const leftClick = () => {
  uni.navigateBack();
};

const onScrollToLower = () => {
  uni.showToast({ title: "到底了", icon: "none" });
};

const onRefresh = () => {
  uni.showToast({ title: "下拉刷新", icon: "none" });
};

const team = () => {
  // uni.showToast({ title: "选择班组", icon: "none" });
};

// 提交报修
const submit = async () => {
  // 必填字段校验
  if (
    !deviceName.value ||
    !applyCode.value ||
    !applyTitle.value ||
    !faultDate.value
  ) {
    uni.showToast({
      title: "请填写必填项",
      icon: "none",
    });
    return;
  }

  const userStore = useUserStore();
  const currentDate = new Date().toISOString().split("T")[0];

  const params = {
    createUser: userStore.userId || -1,
    createDept: userStore.deptId || -1,
    createTime: "",
    updateUser: -1,
    updateTime: "",
    status: 0,
    isDeleted: 0,
    tenantId: "",
    applyCode: applyCode.value,
    applyTitle: applyTitle.value,
    deviceId: -1, // 这里需要从设备选择中获取
    deviceCode: deviceCode.value,
    deviceName: deviceName.value,
    deviceType: deviceType.value,
    deptName: deptName.value,
    storageLocation: storageLocation.value,
    faultTypeId: -1, // 这里需要从故障类型选择中获取
    faultType: faultType.value,
    faultDesc: faultDesc.value,
    faultImage: faultImage.value || "no_image.jpg",
    faultDate: faultDate.value,
    applyDate: currentDate,
    applyDeptId: userStore.deptId || -1,
    applyDept: applyDept.value,
    applyUserId: userStore.userId || -1,
    applyUser: applyUser.value,
    contactInfo: contactInfo.value,
    repairLevel: repairLevel.value
      ? options.value.indexOf(repairLevel.value)
      : 0,
    remark: "",
    orderId: -1,
    orderCode: "",
    statusName: "待处理",
    applyDateStart: "",
    applyDateEnd: "",
  };

  try {
    const res = await saveRepairApply(params);
    if (res && res.code === 200) {
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });
      setTimeout(() => {
        // uni.navigateBack();
        uni.navigateTo({
          url: "/subpkg_institution/repairworkorder/index",
        });
      }, 800);
    } else {
      uni.showToast({
        title: res.msg || "提交失败",
        icon: "none",
      });
    }
  } catch (e) {
    uni.showToast({
      title: "提交异常",
      icon: "none",
    });
  }
};

const handleDeviceSelect = () => {
  uni.navigateTo({
    url: "/subpkg_institution/repairworkorder/deviceSelect",
  });
};

onMounted(() => {
  getFaultTypes();
  uni.$on("deviceSelected", (deviceInfo) => {
    deviceName.value = deviceInfo.deviceName;
    deviceCode.value = deviceInfo.deviceCode;
    deviceModel.value = deviceInfo.deviceModel;
    deviceType.value = deviceInfo.deviceType;
    storageLocation.value = deviceInfo.storageLocation;
    deptName.value = deviceInfo.deptName;
  });
});

onUnmounted(() => {
  uni.$off("deviceSelected");
});
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  background-color: #f6f6f6;
}
.viewport {
  height: 100%;
}
.scroll-view {
  height: 100%;
}
.warp {
  margin-bottom: 120rpx;
  .document {
    .debris {
      display: flex;
      align-items: center;
      height: 100rpx;
      .img {
        width: 60rpx;
        height: 60rpx;
        margin: 0 30rpx;
      }
    }
  }
  .title {
    border-bottom: 1px solid #ccc;
    height: 70rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-right: 30rpx;
  }
  .tishi {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 30rpx;
  }
  .grid-container {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
    padding: 30rpx;
  }

  .grid-item {
    // text-align: center;
    // padding: 20px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    .img {
      width: 100%;
      border-radius: 50%;
      height: auto;
      aspect-ratio: 1/1; /* 指定宽高比为 1:1 */
    }
  }
  .port {
    background-color: #fff;
    margin-bottom: 20rpx;
    .li {
      display: flex;
      align-items: center;
      height: 100rpx;
      padding-left: 40rpx;
      .right {
        margin-left: 30rpx;
        color: #cbb8b8;
      }
    }
    .item {
      // height: 100rpx;
      padding-left: 40rpx;
      padding-bottom: 30rpx;
      .left {
        height: 70rpx;
      }
      .described {
        padding-right: 50rpx;
      }
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100vw;
  background: #fff;
  z-index: 10;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 120rpx;
  .submit-btn {
    width: 90vw;
    height: 80rpx;
    background: #0052d9;
    color: #fff;
    border-radius: 10rpx;
    font-size: 32rpx;
  }
}

.fault-type-popup {
  background-color: #fff;
  .popup-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;

    .popup-buttons {
      .cancel-btn {
        color: #666;
        margin-right: 30rpx;
      }
      .confirm-btn {
        color: #0052d9;
      }
    }
  }

  .fault-type-content {
    display: flex;
    height: 600rpx;

    .parent-list {
      width: 40%;
      height: 100%;
      background-color: #f8f8f8;

      .parent-item {
        padding: 30rpx;
        text-align: center;
        position: relative;

        &.selected {
          color: #0052d9;
          background-color: #fff;

          &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 8rpx;
            height: 32rpx;
            background-color: #0052d9;
            border-radius: 0 4rpx 4rpx 0;
          }
        }
      }
    }

    .child-list {
      flex: 1;
      height: 100%;

      .child-item {
        padding: 30rpx;
        text-align: center;

        &.selected {
          color: #0052d9;
          background-color: #f5f5f5;
        }

        &:active {
          background-color: #f5f5f5;
        }
      }
    }
  }
}
</style>
